/*

This program makes distance indicators for countries from which an MNE imports 
(or to which it exports) and its closet affiliate

*/




 **Set directories
cd ""  /* PROJECT ROOT FOLDER */

/* DEFINE GLOBALS PATHS HERE */

global data "data"
global temp work
global distances "data/distances"
global input_country "input/country_data_input"
global input data
global countrydata data


use firmid iso3 number_man_affiliates using $input/country_imp_aff2007.dta, clear

keep if number_man_aff >= 1 & number_man_aff != .
drop number

ren iso3 iso3_o
joinby iso3_o using $distances/distance_mat_abb.dta



* getting rid of iso3_o = iso3_d cases, i.e., don't count the closest affil
* as 0-500km if the affil is in the country
* just set it to very high number, and correct for this later
replace dist_harm = 99999 if iso3_o == iso3_d 

* find the closest affiliate
* do not count US as an affiliate
 collapse(min) dist_harm, by(firmid iso3_d) 
 
 
 
 gen aff0_500 = (dist_harm <= 500)
 gen aff501_1000 = (dist_harm > 500 & dist_harm <= 1000)
 gen aff1001_2000 = (dist_harm > 1000 & dist_harm <= 2000)
 gen aff2001_4000 = (dist_harm > 2000 & dist_harm <= 4000)
 gen aff4001 = (dist_harm > 4000 & dist_harm < 99999)
 
 ren dist_harm dist_closest_affil
 replace dist_closest_affil = . if dist_closest_affil == 99999
 
 
 ren iso3_d iso3
 
 save $distances/closest_affiliate_indicators.dta, replace
 
 
 
 
 * doing the same thing for importers, exporters
 * the code is literally exactly the same, just joinby importer or exporter 
 * rather than affiliate
use firmid iso3 importer using $input/country_imp_aff2007.dta, clear
keep if importer == 1

ren iso3 iso3_o
joinby iso3_o using $distances/distance_mat_abb.dta

replace dist_harm = 99999 if iso3_o == iso3_d 
 collapse(min) dist_harm, by(firmid iso3_d) 
 
 
 
 gen imp0_500 = (dist_harm <= 500)
 gen imp501_1000 = (dist_harm > 500 & dist_harm <= 1000)
 gen imp1001_2000 = (dist_harm > 1000 & dist_harm <= 2000)
 gen imp2001_4000 = (dist_harm > 2000 & dist_harm <= 4000)
 gen imp4001 = (dist_harm > 4000 & dist_harm < 99999)
 
 ren dist_harm dist_closest_imp
 replace dist_closest_imp = . if dist_closest_imp== 99999
 
 
 ren iso3_d iso3
 
 save $distances/closest_import_indicators.dta, replace
 
 
 
 
 
 
 use firmid iso3 exporter using $input/country_imp_aff2007.dta, clear
keep if exporter == 1

ren iso3 iso3_o
joinby iso3_o using $distances/distance_mat_abb.dta

replace dist_harm = 99999 if iso3_o == iso3_d 
 collapse(min) dist_harm, by(firmid iso3_d) 
 
 
 
 gen exp0_500 = (dist_harm <= 500)
 gen exp501_1000 = (dist_harm > 500 & dist_harm <= 1000)
 gen exp1001_2000 = (dist_harm > 1000 & dist_harm <= 2000)
 gen exp2001_4000 = (dist_harm > 2000 & dist_harm <= 4000)
 gen exp4001 = (dist_harm > 4000 & dist_harm < 99999)
 
 ren dist_harm dist_closest_exp
 replace dist_closest_exp= . if dist_closest_exp== 99999
 
 
 ren iso3_d iso3
 
 save $distances/closest_export_indicators.dta, replace
